<template>
  <div class="plot-info">
    <el-row>
      <el-col :span="24">
        <!-- 条件查询区域 -->
        <el-form ref="queryFormRef" :model="queryForm" inline size="mini">
          <el-form-item label="小区名称" prop="plotName">
            <el-input v-model="queryForm.plotName" placeholder="请输入小区名称" />
          </el-form-item>
          <el-form-item label="小区编码" prop="plotNo">
            <el-input v-model="queryForm.plotNo" placeholder="请输入小区编码" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button plain @click="handleReset">重置</el-button>
            <el-button type="primary" plain @click="handleAdd">添加</el-button>
          </el-form-item>
        </el-form>

        <!-- 小区列表表格 -->
        <el-table :data="plotList" style="width: 100%" border stripe ref="table"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" />
          <el-table-column type="index" label="序号" width="50" align="center" />
          <el-table-column prop="plotName" label="小区名称" align="center" />
          <el-table-column prop="city" label="城市" align="center" />
          <el-table-column prop="plotNo" label="小区编码" align="center" show-overflow-tooltip />
          <el-table-column prop="cityDtl" label="小区地址" align="center" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip />
          <el-table-column align="center" label="操作" width="250">
            <template #default="{ row }">
              <el-row class="flex-end">
                <el-button type="success" size="small" @click="handleSelect(row.plotId)"
                  v-if="!isCurrentPlot(row.plotId)">切换小区</el-button>
                <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
              </el-row>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-row type="flex" justify="center" style="margin-top: 10px;"></el-row>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page.sync="paginate.pageNum" :page-sizes="[5, 10, 15]" :page-size.sync="paginate.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="paginate.total">
        </el-pagination>


        <!-- 弹窗 -->
        <el-dialog :visible.sync="dialog.visible" width="50%" @close="handleClose">
          <template #title>{{ dialog.isEdit ? "编辑" : "添加" }}</template>
          <el-form width="80px" label-position="left" size="small" :model="dialog.form" :rules="dialog.rules"
            hide-required-asterisk ref="dialogFormRef">

            <el-form-item label="小区名字" prop="plotName">
              <el-input v-model="dialog.form.plotName" style="width: 300px;"></el-input>
            </el-form-item>

            <el-form-item label="小区地址" prop="cityDtl">
              <el-input v-model="dialog.form.cityDtl" style="width: 300px;"></el-input>
            </el-form-item>


            <el-form-item label="小区地区" prop="city">

              <!-- 选择省份 -->
              <el-form-item prop="provId" style="display: inline-block; margin-right: 20px;">
                <el-select v-model="dialog.form.provId" placeholder="请选择省份" style="width: 120px;"
                  @change="handleProvinceChange">
                  <el-option v-for="item in provinces" :key="item.provId" :label="item.provName"
                    :value="item.provId"></el-option>
                </el-select>
              </el-form-item>


              <!-- 选择城市 -->
              <el-form-item prop="cityId" style="display: inline-block; margin-right: 20px;">
                <el-select v-model="dialog.form.cityId" placeholder="请选择城市" style="width: 120px;"
                  @change="handleCityChange">
                  <el-option v-for="item in cities" :key="item.cityId" :label="item.cityName"
                    :value="item.cityId"></el-option>
                </el-select>
              </el-form-item>


              <!-- 选择区县 -->
              <el-form-item prop="areaId" style="display: inline-block;">
                <el-select v-model="dialog.form.areaId" placeholder="请选择区县" style="width: 120px;" clearable>
                  <el-option v-for="item in areas" :key="item.areaId" :label="item.areaName"
                    :value="item.areaId"></el-option>
                </el-select>
              </el-form-item>


            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button size="small" @click="handleClose">取 消</el-button>
            <el-button type="primary" size="small" @click="handleSubmit">确 定</el-button>
          </span>
        </el-dialog>


      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listPlot, updatePlot, addPlot, deletePlot } from '@/api/plot'
import { areaList } from '@/api/area'
import { checkQueryInput, restForm } from '@/utils/tool'


export default {
  name: 'PlotInfo',
  data() {
    return {
      // 阻止重复提交
      isLock: false,

      // 小区列表
      plotList: [],

      // 查询表单数据
      queryForm: {
        plotName: '',
        plotNo: ''
      },

      // 分页参数
      paginate: {
        pageSize: 5,
        pageNum: 1,
        total: 0
      },

      // 省市区数据
      provinces: [],
      cities: [],
      areas: [],
      allAreaData: [],

      // 弹窗
      dialog: {
        //是否为编辑状态
        isEdit: false,
        visible: false,

        form: {
          // city: undefined,
          cityDtl: "",
          coordinate: undefined,
          plotId: undefined,
          plotName: "",
          provId: undefined,
          areaId: undefined,
          cityId: undefined,
        },

        // 表单校验
        rules: {
          plotName: [{
            required: true,
            message: "请输入小区名字",
            trigger: "blur"
          }],
          cityDtl: [{
            required: true,
            message: "请输入小区详情地址",
            trigger: "blur"
          }],
          provId: [{
            required: true,
            message: "请选择省份",
            trigger: "change"
          }],
          cityId: [{
            required: false,
            message: "请选择城市",
            trigger: "change"
          }],
          areaId: [{
            required: false,
            message: "请选择区县",
            trigger: "change"
          }]
        },
      },
      // 批量删除
      ids: [],//存储选中的所有小区ID
      single: true,//标记是否不是单选
      multiple: false//标记是否没有选中数据
    }

  },


  created() {
    this.getPlotList()
    this.getAreaData()
  },


  computed: {
    //获取当前小区的id
    currentPlotId() {
      return this.$store.state.plot?.currentPlot?.plotId || undefined
    },

  },



  methods: {
    // 获取小区列表
    getPlotList() {
      const { total, ...rest } = this.paginate
      console.log(this.queryForm);
      
      return listPlot({
        ...rest, ...this.queryForm
      }).then(res => {
        console.log(res);
        this.plotList = res.rows || []
        this.paginate.total = res.total || 0
        return res
      })
    },

    // 分页切换
    handleSizeChange() {
      this.getPlotList()
    },
    handleCurrentChange() {
      this.getPlotList()
    },

    // 切换小区
    handleSelect(plotId) {
      this.$store.dispatch('plot/getPlotDetail', plotId).then(() => {
        this.$message.success("切换小区成功")
        // console.log("小区id",plotId);

      })
    },

    // 判断是否为当前选中的小区
    isCurrentPlot(plotId) {
      return plotId === this.currentPlotId
    },

    // 获取省市区数据
    getAreaData() {
      areaList().then(res => {
        console.log("省市区", res);
        this.allAreaData = res.data || []
        // 获取省份数据
        this.provinces = this.allAreaData
        // console.log("省份数据", this.provinces);
      })
    },



    // 根据省份id查询省份名称
    getProvinceName(provId) {
      const province = this.provinces.find(p => p.provId === provId)
      return province ? province.provName : ""
    },

    // 根据省份ID和城市ID查询城市名称
    getCityName(provId, cityId) {
      const province = this.provinces.find(p => p.provId === provId)
      if (!province || !province.cityAreaVos) return ""

      const city = province.cityAreaVos.find(c => c.cityId === cityId)
      return city ? city.cityName : ""
    },

    // 根据城市ID和区县ID查询区县名称
    getAreaName(cityId, areaId) {
      const city = this.cities.find(c => c.cityId === cityId)
      if (!city || !city.areaVos) return ""

      const area = city.areaVos.find(a => a.areaId === areaId)
      return area ? area.areaName : ""
    },

    // 拼接省市区
    getFullAreaName(provId, cityId, areaId) {
      const provinceName = this.getProvinceName(provId)
      const cityName = this.getCityName(provId, cityId)
      const areaName = this.getAreaName(cityId, areaId)
      return {
        provinceName,
        cityName,
        areaName,
        // .join()将数组的所有元素全部拼接成字符串，并返回这个字符串
        fullName: [provinceName, cityName, areaName].filter(name => name).join('')
      };
    },



    // 根据省份ID获取城市列表
    getCities(provId) {
      let provinces = null
      for (let i = 0; i < this.allAreaData.length; i++) {
        if (this.allAreaData[i].provId === provId) {
          provinces = this.allAreaData[i]
          break
        }
      }

      if (provinces && provinces.cityAreaVos) {
        this.cities = provinces.cityAreaVos
      } else {
        this.cities = []
      }

      this.areas = []
      this.dialog.form.cityId = undefined
      this.dialog.form.areaId = undefined

    },

    // 根据城市ID获取区县列表
    getAreas(cityId) {
      let city = null
      for (let i = 0; i < this.cities.length; i++) {
        if (this.cities[i].cityId === cityId) {
          city = this.cities[i]
          break
        }
      }

      if (city && city.areaVos) {
        this.areas = city.areaVos
      } else {
        this.areas = []
      }

      this.dialog.form.areaId = undefined
    },


    // select的change事件，选中省份时加载对应的城市信息
    handleProvinceChange(provId) {
      if (provId) {
        this.getCities(provId)
      } else {
        this.cities = []
        this.areas = []
        this.dialog.form.cityId = undefined
        this.dialog.form.areaId = undefined
      }
    },

    // select的change事件，选中城市时加载对应的区县信息
    handleCityChange(cityId) {
      if (cityId) {
        this.getAreas(cityId)
      } else {
        this.areas = []
        this.dialog.form.areaId = undefined
      }
    },


    // 查询
    handleQuery() {
      const hasInput = checkQueryInput(this.queryForm)
      if (!hasInput) return this.$message.warning("当前没有输入值，请至少输入一项数据!!")
      this.paginate.pageNum = 1
      this.getPlotList().then((res) => {
        console.log("表单信息",res);
        
        this.$message.success("查询成功")
      })
    },

    // 重置
    handleReset() {
      restForm(this.$refs.queryFormRef)
      this.paginate.pageNum = 1
      this.getPlotList().then(() => {
        this.$message.success("操作成功")
      })
    },

    // 添加
    handleAdd() {
      this.dialog.visible = true
      this.dialog.isEdit = false
      this.cities = []
      this.areas = []
      // 重置表单
      this.$refs['dialogFormRef']
    },

    // 编辑,利用async await 控制异步的顺序，使得数据加载快速有序
    async handleEdit(row) {
      this.dialog.visible = true
      this.dialog.isEdit = true

      // console.log("行数据", row);

      // 先回显基础字段
      this.dialog.form = {
        plotName: row.plotName || "",
        cityDtl: row.cityDtl || "",
        coordinate: row.coordinate || "",
        plotId: row.plotId,
        provId: undefined,
        cityId: undefined,
        areaId: undefined
      };


      let provId, cityId, areaId;

      const coordinateStr = row.coordinate || row.city || ""
      // console.log(", coordinateStr);
      // console.log("信息编码和名称",row.coordinate,row.city);


      if (coordinateStr) {
        const ids = coordinateStr.split(',').map(item => {
          const num = Number(item.trim())
          return isNaN(num) ? undefined : num
        });

        // 通过数组的解构赋值，将处理过的id分别赋值
        [provId, cityId, areaId] = ids
      }

      // 设置省份并加载城市
      if (provId) {
        // console.log("设置省份ID:", provId);
        this.dialog.form.provId = provId;

        // 等待DOM更新
        await this.$nextTick();

        // 加载城市数据
        this.getCities(provId);

        // 等待城市数据加载完成
        await new Promise(resolve => setTimeout(resolve, 100))

        if (cityId) {
          // console.log("设置城市ID:", cityId);
          this.dialog.form.cityId = cityId;

          // 等待DOM更新
          await this.$nextTick();

          // 加载区县数据
          this.getAreas(cityId);

          // 等待区县数据加载完成
          await new Promise(resolve => setTimeout(resolve, 100));

          if (areaId) {
            // console.log("设置区县ID:", areaId)
            this.dialog.form.areaId = areaId
          }
        }
      }
    },

    // 提交
    handleSubmit() {
      // 如果当前正在操作则阻止重复操作
      if (this.isLock) return

      this.$refs["dialogFormRef"].validate(valid => {
        console.log("表单校验结果:", valid)
        if (!valid) return

        // 上锁，禁止重复触发
        this.isLock = true

        const { form, isEdit } = this.dialog
        const { provId, cityId, areaId, ...rest } = form

        const coordinateStr = `${provId},${cityId},${areaId}`

        const areaNames = this.getFullAreaName(provId, cityId, areaId);

        const params = {
          plotName: form.plotName,
          cityDtl: form.cityDtl,
          city: areaNames.fullName,
          coordinate: coordinateStr,
        }

        // if (isEdit) {
        //   // 编辑
        //   updatePlot(this.dialog.form).then(res => {
        //     this.$message.success(res.msg || '操作成功')
        //     this.dialog.visible = false
        //     this.getListClass()
        //     this.handleClose()
        //   })
        // } else {
        //   // 添加
        //   addPlot(this.dialog.form).then(res => {
        //     this.$message.success(res.msg || '操作成功')
        //     this.dialog.visible = false
        //     this.getListClass()
        //     this.handleClose()

        //   })
        // }


        // 除了调用的接口不一样，逻辑几乎是一样的，换成利用三段式判断是否为编辑并调用对应接口

        // 编辑时添加plotId
        if (isEdit) {
          params.plotId = form.plotId
        }

        // console.log("提交参数:", params);

        const apiCall = isEdit ? updatePlot : addPlot

        apiCall(params).then(res => {
          this.$message.success(res.msg || "操作成功")
          this.getPlotList()
          this.handleClose()
          // 提交成功后解锁
          this.isLock = false
        })
      })
    },


    // 关闭弹窗
    handleClose() {
      this.dialog.visible = false;
      // 清空表单
      restForm(this.$refs['dialogFormRef'])
    },


    // 批量删除的选中事件
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.plotId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },



    // 删除
    handleDelete(row) {
      // 拿到被选中的小区的id
      const plotIds = this.ids.length > 0 ? this.ids : [row.plotId]

      // 把id的数组转成字符串并用","分隔
      const plotIdsStr = plotIds.join(',')

      //删除的是否是当前小区
      const isDelCurPlot = plotIds.includes(this.currentPlotId)

      this.$confirm(`确定删除小区编号为【${plotIdsStr}】的小区吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 等待接口执行完成
        return deletePlot(plotIdsStr).then(() => {
          //若删除的是当前小区，清空 Vuex 中的当前小区状态
          if (isDelCurPlot) {
            this.$store.commit('plot/setCurrentPlot', undefined)
          }
          this.getPlotList()
          this.$message.success("删除成功")
          this.$refs.table.clearSelection()
        })
      }).catch((err) => {
        console.log(err)
      })

    },



  }
}

</script>

<style lang="scss" scoped>
.plot-info {
  padding: 20px;
}
</style>